//
//  ComposeViewController.swift
//  WeiBoSwift
//
//  Created by rong on 15/7/7.
//  Copyright © 2015年 rong. All rights reserved.
//

import UIKit
import FFAutoLayout
import SVProgressHUD

/// 微博文字的最大长度
private let statusMaxLength = 140

class ComposeViewController: UIViewController {
    
    
    private lazy var EmoticonsVC: EmoticonsController = EmoticonsController {[unowned self]  (emoticon) -> () in
        self.textView.insertEmoticons(emoticon)
    }
    

    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor.whiteColor()
        
        //添加子控件
        addChildViewController(EmoticonsVC)
        
        //添加图片选择控制器
        addChildViewController(photoSelectorVC)
        
        //view.addSubview(photoSelectorView)  如果放到这个地方，会被其他视图盖住
        
        // 取消自动调整滚动视图缩紧
        //automaticallyAdjustsScrollViewInsets = false
        
        prepareForNavigationBar()
        prepareForTextView()
        prepareForToolBar()
        
        //添加图片选择器视图  !!!!!!!!! 注意添加视图  和  设置视图的约束  的前后关系
        view.addSubview(photoSelectorView)
        prepareForOthers()
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //注册键盘通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit {
        //注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //键盘通知变化处理函数
    /*
    NSConcreteNotification 0x7fd81d3711b0 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
    
        UIKeyboardAnimationCurveUserInfoKey = 7;
        UIKeyboardAnimationDurationUserInfoKey = "0.25";
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
        UIKeyboardIsLocalUserInfoKey = 1;
    }}
    NSConcreteNotification 0x7fd81ac544c0 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
    
        UIKeyboardAnimationCurveUserInfoKey = 7;   //动画曲线类型
        UIKeyboardAnimationDurationUserInfoKey = "0.25";            //动画持续时间
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 538}";    //键盘动画起始时的中心点
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 796}";      //键盘动画结束时的中心点
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 409}, {375, 258}}"; //键盘动画起始时的大小
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 667}, {375, 258}}"; //键盘动画结束时的大小
        UIKeyboardIsLocalUserInfoKey = 1;
    }}
    
    667 - 409 = 258
    
    //最后一个属性   UIKeyboardIsLocalUserInfoKey，系统键盘打开，为1，系统键盘关闭，也是1
     ！！！但是，如果键盘是 通过 textView的 resignfirstResponse方法注销的 时候，UIKeyboardIsLocalUserInfoKey ＝ 0
    如果 textView 再获得 becomeFirstResponse，此时 UIKeyboardIsLocalUserInfoKey ＝ 1
    
    系统键盘 关闭：  UIKeyboardIsLocalUserInfoKey = 0; 如果为0， 此时不做动画
    系统键盘 打开：  UIKeyboardIsLocalUserInfoKey = 1;
    */
    
    //toolBar出现 是否动画  的标志
    private var toolBarAnimationFlag = false
    
    func keyboardChanged(notification: NSNotification) {
        print(notification)
        
        //键盘 的 rect
        let rect = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        //键盘动画时长
        var duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        let isAnimation = notification.userInfo!["UIKeyboardIsLocalUserInfoKey"]!.boolValue
        
        if !isAnimation {
            toolBarAnimationFlag=true
            return
        }
        
        duration = toolBarAnimationFlag ? 0:duration
        toolBarAnimationFlag = false
        
        //设置键盘高度
        toolBarBottomCons?.constant = -(view.bounds.height - rect.origin.y) //rect.size.height
        
        //为了让键盘 弹出 和  toolBar 的高度变化 的 动画一致，
        UIView.animateWithDuration(duration) {  self.view.layoutIfNeeded() }
        
    }
    
    private var firstLoadView = true
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if firstLoadView {
            //在这里打开键盘
            textView.becomeFirstResponder()
            firstLoadView = false
        }
        
    }
    
    override func viewWillDisappear(animated: Bool) {
        //在这里关闭键盘
        textView.resignFirstResponder()
    }
    
    //设置 NavigationBar 的控件
    private func prepareForNavigationBar() {
        
        //左侧按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        //右侧按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        navigationItem.rightBarButtonItem?.enabled = false
        
        //中间的view
        let titleView = UIView()
        let titleLabel = UILabel(content: "发微博", color: UIColor(white: 0.0, alpha: 1.0), fontSize: 15)
      
        let nameLabel = UILabel(content: (sharedUserAccount?.name ?? ""), color: UIColor(white: 0.0, alpha: 0.5), fontSize: 13)
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        //自动布局
        titleLabel.ff_AlignInner(ff_AlignType.BottomCenter, referView: titleView, size: nil)
        nameLabel.ff_AlignInner(ff_AlignType.TopCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView
    }
    
    //设置 textView 控件
    private func prepareForTextView() {
        
        view.addSubview(textView)
        //textView.text = "分享新鲜事...分享新鲜事...分享新鲜事...分享新鲜事...分享新鲜事..."
        textView.font = UIFont.systemFontOfSize(18)
        
        /*UITextView 继承于 UIScrollView， 所以可以进行滚动
        UIScrollView的两个属性：
        var bounces: Bool 
            // default YES. if YES, bounces past edge of content and back again
        var alwaysBounceVertical: Bool 
            // default NO. if YES and bounces is YES, even if content is smaller than bounds, allow drag vertically
        */
        //设置垂直滚动
        textView.alwaysBounceVertical = true
        textView.bounces = true
        //关闭键盘的 模式： 滚动关闭键盘
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        //设置键盘输入视图的
        //textView.inputAccessoryView = prepareForToolBar()
        
        textView.delegate = self
        
        
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.text = "分享新鲜事..."
        placeHolderLabel.font = UIFont.systemFontOfSize(18)
        placeHolderLabel.sizeToFit()
        
        print("发送微博 ＝＝＝》 \(view.frame)")
        
        textView.ff_Fill(view)
        placeHolderLabel.ff_AlignInner(ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
    }
    
    //设置键盘 上方的 toolBar
    /* 下方的 toolBar
    compose_toolbar_picture     compose_mentionbutton_background  compose_trendbutton_background
    
    compose_emoticonbutton_background   compose_addbutton_background
    
    */
    //private func prepareForToolBar() -> UIToolbar {
      private func prepareForToolBar() {
    
        //let toolBar = UIToolbar(frame: CGRectMake(0, 0, 0, 44))
        
        //最后一个按钮的 图片做的不好，设置 toolBar 的颜色跟
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        let toolBarItems = [["imageName": "compose_toolbar_picture", "actionName": "selectPicture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "insertEmoticon"],
                            ["imageName": "compose_addbutton_background"]]
        
        //定义一个 装 UIBarButtonItem 的数组 item["imageName"]
        var itemMutableArray = [UIBarButtonItem]()
        
        for item in toolBarItems {
            
            itemMutableArray.append(UIBarButtonItem(imageName: item["imageName"]!, highlightedImageName: nil, target: self, actionName: item["actionName"]))
            itemMutableArray.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        itemMutableArray.removeLast()
        
        //!!!加上这句话
        toolBar.items = itemMutableArray
        
        //添加toolBar
        view.addSubview(toolBar)
        let cons = toolBar.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: nil)
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolBar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["toolBar": toolBar]))
        
        //记录工具栏底部约束
        toolBarBottomCons = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        //return toolBar
    }
    
    func prepareForOthers() {
    
        view.addSubview(lengthLabel)
       // lengthLabel.text = "-10"
//        lengthLabel.ff_AlignInner(ff_AlignType.BottomRight, referView: textView, size: nil, offset:                   CGPoint(x: -12, y: -320))
        
        lengthLabel.ff_AlignInner(ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -12, y: -12))
        
        //关于图片选择器的布局
        photoSelectorView.ff_AlignVertical(ff_AlignType.TopCenter, referView: toolBar, size: nil)
        //图片选择器 的 宽度 和 高度
        view.addConstraint(NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0))
        //刚开始的时候，高度为0 ，点击了图片选择器按钮之后，才出现
        photoSelectorHeightCons = NSLayoutConstraint(item: photoSelectorView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 0)
        view.addConstraint(photoSelectorHeightCons!)
    }

    //toolBar上面的 点击函数
    func selectPicture() {
        
        //print("点击选择图片按钮")
        photoSelectorHeightCons?.constant = view.bounds.height / 3
        
        //出现图片选择界面之后，关闭键盘
        textView.resignFirstResponder()
        
        //将toolBar的  放到屏幕的最下发
        toolBarBottomCons?.constant = 0
    }
    
    //编辑插入表情
    func insertEmoticon() {
        
        print("编辑插入表情")
        
        //！！！如果 textView.inputView 是 nil , 说明使用的是系统的输入法
        print(textView.inputView)
        
        //如果切换系统输入法 到自定义的输入法，需要先将系统的输入法关掉
        textView.resignFirstResponder()
        
        //更换键盘输入视图
        textView.inputView = (textView.inputView == nil) ? EmoticonsVC.view : nil
        
        // 然后重新设置焦点
        textView.becomeFirstResponder()
    }
    
    //关闭
    func close() {
        //关掉界面之前，关闭 SVProgressHUD 的显示
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //发布微博
    //接口： statuses/update   发布一条微博信息
    //   statuses/upload   上传图片 并且 发布一条微博
    func send() {
        
        //如果这里用 textView.text， 只能发送文字信息，头像会过滤掉，用空格代替
        
        //判断是否有内容
        if textView.emoticonText().characters.count <= 0 {
            return
        }
        
        if textView.emoticonText().characters.count > statusMaxLength {
            
            SVProgressHUD.showInfoWithStatus("文本内容过长", maskType: SVProgressHUDMaskType.Black)
            return
        }
        
        SVProgressHUD.show()
        NetworkTools.sharedNetworkTools().postStatus(textView.emoticonText(), image:photoSelectorVC.photos.last) { (error) -> () in
            
            if error != nil {
                SVProgressHUD.showErrorWithStatus("您的网络不给力")
                return
            }
            
            //发布成功之后关闭窗口
            self.close()
        }
    }
    
    //懒加载控件
    private lazy var textView = UITextView()
    private lazy var placeHolderLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 18)
    //提示微博字数的label控件
    private lazy var lengthLabel = UILabel(color: UIColor.redColor(), fontSize: 12)
    //原来的toolbar依托于 textView 的 inputAccessoryView, 键盘没了，toolbar也跟着没了
    private lazy var toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 0, height: 44))
    // 记录工具栏底部约束
    private var toolBarBottomCons: NSLayoutConstraint?
    
    
    //照片选择控制器
    private lazy var photoSelectorVC: PhotoSelectorViewController = PhotoSelectorViewController()
    //照片选择视图
    private lazy var photoSelectorView: UIView = self.photoSelectorVC.view
    //照片选择视图的“高度”约束
    private var photoSelectorHeightCons: NSLayoutConstraint?
    
}

extension ComposeViewController: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeHolderLabel.hidden = textView.hasText()
        
        print(textView.emoticonText().characters.count)
        
        let len = statusMaxLength - textView.emoticonText().characters.count
        lengthLabel.text = (len == 0) ? "" : String(len)
        lengthLabel.textColor = len > 0 ? UIColor.grayColor() : UIColor.redColor()
    }
}
